package com.ejlchina.common.captcha;

import java.util.HashMap;
import java.util.Map;


/**
 * 
 * 验证码内存存储器
 * 
 * @author Troy
 *
 */
public class MemoryCaptchaService implements CaptchaService {

	
	private final long DAY = 24 * 60 * 60;		// 计数周期
	
	private Map<String, MemoryCaptcha> cache = new HashMap<>();

	
	@Override
	public MemoryCaptcha findCaptcha(String phone) {
		return cache.get(phone);
	}


	@Override
	public int findSendTimesToday(String phone) {
		MemoryCaptcha captcha = findCaptcha(phone);
		if (captcha == null) {
			return 0;
		}
		long now = System.currentTimeMillis() / 1000;
		if (captcha.getCountTime() < now - DAY) {
			captcha.setCount(0);
			captcha.setCountTime(now);
		}
		return captcha.getCount();
	}

	
	@Override
	public void save(String phone, String code, int expireSeconds) {
		long now = System.currentTimeMillis() / 1000;
		MemoryCaptcha captcha = findCaptcha(phone);
		if (captcha == null) {
			captcha = new MemoryCaptcha();
			captcha.setCountTime(now);
		}
		captcha.setCode(code);
		captcha.setExpireTime(now + expireSeconds);
		captcha.setCount(captcha.getCount() + 1);
		captcha.setChecked(false);
		cache.put(phone, captcha);
	}

	
	@Override
	public void markCaptchaChecked(String phone, Captcha captcha) {
		MemoryCaptcha mcaptcha = (MemoryCaptcha) captcha;
		mcaptcha.setChecked(true);
		cache.put(phone, mcaptcha);
	}

	/**
	 * 内存验证码
	 * 
	 * @author Troy.Zhou
	 *
	 */
	public class MemoryCaptcha implements Captcha {
	
		private String code;
		private boolean checked;
		private long expireTime;
		private long countTime;
		private int count; 			// 每日发送条数计数
	
		@Override
		public String getCode() {
			return code;
		}
	
		@Override
		public boolean isExpired() {
			return expireTime < System.currentTimeMillis() / 1000;
		}
		
		@Override
		public boolean isChecked() {
			return checked;
		}
	
		public void setChecked(boolean checked) {
			this.checked = checked;
		}

		public int getCount() {
			return count;
		}
	
		public void setCode(String code) {
			this.code = code;
		}
	
		public void setExpireTime(long expireTime) {
			this.expireTime = expireTime;
		}
	
		public void setCount(int count) {
			this.count = count;
		}

		public long getCountTime() {
			return countTime;
		}

		public void setCountTime(long countTime) {
			this.countTime = countTime;
		}
		
	}

	
}
